/**
 * Created with IntelliJ IDEA.
 * User: zzl
 * Date: 12-12-6
 * To change this template use File | Settings | File Templates.
 */
(function ($, undefined) {

    var ProgressBar = function (container, options) {
        this.$container = $(container);
        this.options = options;
//        this._value = options.value || 0;
        this.setup();
    };

    var proto = { constructor: ProgressBar };
    ProgressBar.prototype = proto;

    proto.setup = function () {
        var me = this;

        var value = me.options.value || parseInt(me.$container.text()) || 0;
        me._value = value;

        var percent = value / me.options.max * 100;
        var percentText = Math.floor(percent) + '%';
        var contrastValueWidth = percent? (100 / percent * 100) + '%': 0;

        var html = '<div class="progressBarContents">' +
            '<div class="value base">' + percentText + '</div>' +
            '<div class="progress" style="width:' + percent + '%">' +
            '<div class="value contrast" style="width:' + contrastValueWidth + ';">' + percentText + '</div>' +
            '</div>' +
            '</div>';

        me.$container[0].innerHTML = html;

    };

    proto.value = function(value) {
        var me = this;
        if(value === undefined) {
            return me._value;
        }
        if(value == me._value) {
            return;
        }
        if(isNaN(value) || value < 0 || value > 100) {
            value = me._value;
        }
        me._value = value;
        var percent = value / me.options.max * 100;
        var percentText = Math.floor(percent) + '%';

        var $children = me.$container.children().children();

        var $baseValue = $($children[0]);
        var $progress = $($children[1]);
        var $contrastValue = $progress.children();

        $baseValue[0].innerText = percentText;
        $contrastValue[0].innerText = percentText;

        $progress[0].style.width = percent + '%';
        $contrastValue[0].style.width = percent? (100 / percent * 100) + '%': 0;
    };


    $.fn.progressBar = $.addPluginFn('progressBar', ProgressBar, {
        min: 0,
        max: 100,
        value: 0
    });

})(jQuery);